using Microsoft.Xna.Framework.Graphics;

namespace BlobSim.Shapes
{
    class Cylinder : Shape
    {
        #region Private Data

        private GraphicsDevice _device;
        private VertexBuffer _vertexBuffer;
        private IndexBuffer _indexBuffer;
        private float _radius;
        private int _slices;
        private float _height;
        private int _segments;

        #endregion

        #region Constructor

        public Cylinder(GraphicsDevice device, float radius, int slices, float height, int segments)
        {
            _device = device;
            _radius = radius;
            _slices = slices;
            _height = height;
            _segments = segments;
            BuildCylinder();
        }

        #endregion

        #region Overrides

        public override VertexBuffer VertexBuffer { get { return _vertexBuffer; } }
        public override IndexBuffer IndexBuffer { get { return _indexBuffer; } }

        public override void Draw()
        {
            _device.DrawIndexedPrimitives(PrimitiveType.TriangleStrip, 0, 0, _slices, 0, _slices - 2);
            _device.DrawIndexedPrimitives(PrimitiveType.TriangleStrip, _slices, 0, _slices, _slices, _slices - 2);

            for (int i = 0; i < _segments; i++)
                _device.DrawIndexedPrimitives(PrimitiveType.TriangleStrip, 2 * _slices + i * (_slices + 1), 0, 2 * (_slices + 1), 2 * _slices, 2 * _slices);
        }

        #endregion

        #region Private Implementation

        private void BuildCylinder()
        {
            VertexPositionNormalTexture[] vertices;
            ushort[] indices;
            Utils.BuildCylinder(_radius, _slices, _height, _segments, out vertices, out indices);

            _vertexBuffer = new VertexBuffer(_device, typeof(VertexPositionNormalTexture), vertices.Length, BufferUsage.None);
            _vertexBuffer.SetData(vertices);
            _indexBuffer = new IndexBuffer(_device, typeof(ushort), indices.Length, BufferUsage.None);
            _indexBuffer.SetData(indices);
        }

        #endregion
    }
}
